module EasyForm
  class ErrorNotification
    delegate :object, :object_name, :template, to: :@builder

    def initialize(builder, options)
      @builder = builder
      @message = options.delete(:message)
      @options = options
    end

    def render
      return unless has_error?
      template.content_tag error_notification_tag, error_message, html_options
    end

    protected
    def has_error?
      object && object.respond_to?(:errors) && object.errors.present?
    end

    def error_message
      (@message || translate_error_notification).html_safe
    end

    def error_notification_tag
      EasyForm.error_notification_tag
    end

    def html_options
      @options[:class] = "#{EasyForm.error_notification_class} #{@options[:class]}".strip
      @options
    end

    def translate_error_notification
      lookups = []
      lookups << object_name.to_s.to_sym
      lookups << :default_message
      lookups << 'Please review the problems below:'
      I18n.t(lookups.shift, scope: "#{EasyForm.i18n_scope}.error_notification", default: lookups)
    end

  end
end